package stancel.peter.smslogger.background;

import java.util.Collections;
import java.util.List;

import stancel.peter.smslogger.SMSLogger;
import stancel.peter.smslogger.Sms;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;

/**
 * Sluzba, ktora sa spusti po prijati sms.
 * Ma za ulohu vytvorit objekt <b>Sms</b> a ulozit ho do listu.
 * @author Peter Stancel
 */
public class SMSLoggerService extends Service{

	/**
	 * Zisti, ci cislo prijatej sms sa nachadza v kontaktoch.
	 * Ak ano, najde meno kontaktu a ulozi ho do <i>sms</i>.
	 * Skontroluje velkost posledneho listu, ak uz obsahuje 200
	 * smsiek, vytvori novy, do ktoreho ulozi <i>sms</i> a zvysi
	 * <i>fileNumber</i> o 1. List ulozi do suboru a aktualizuje widget.
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		SMSLogger smsLogger = (SMSLogger) getApplication();
		int fileNumber = smsLogger.getMaxFileNumber();
		List<Sms> list = smsLogger.loadFromFile(fileNumber);

		// skontroluje cislo prijatej sms v kontaktoch, ak existuje kontakt s danym cislom, ulozi jeho meno
		String number = intent.getStringExtra("sms_number");
		String WHERE_CONDITION = "1=1) GROUP BY (" + Phone.NUMBER;
	    String[] PROJECTION = {Phone.DISPLAY_NAME, Phone.NUMBER};

		Cursor cursor = getContentResolver().query( Phone.CONTENT_URI, PROJECTION, WHERE_CONDITION, null, null);
		String name = null;
		while(cursor.moveToNext()){
			if(PhoneNumberUtils.compare(cursor.getString(1), number)){
				name = cursor.getString(0);
				break;
			}
		}
		Sms sms;
		if(name != null){
			sms = new Sms(intent.getStringExtra("sms_time"), number, intent.getStringExtra("sms_text"), name);
		} else{
			sms = new Sms(intent.getStringExtra("sms_time"), number, intent.getStringExtra("sms_text"));
		}

		// kontrola a ulozenie
		if(list.size() >= 200){
			fileNumber++;
			smsLogger.setFileNumber(fileNumber);
			list.clear();
		} 
		Collections.reverse(list);
		list.add(sms);
		Collections.reverse(list);
		smsLogger.saveToFile(fileNumber, list);

		// spusti sluzbu pre aktualizaciu widgetu
		Intent intent2 = new Intent(this, SMSWidgetService.class);
		startService(intent2);

		stopSelf();
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
